package com.winchain.provider.expiration.cmd;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.basic.exception.ExtException;
import com.winchain.chainbill.bill.base.po.CbDfrl;
import com.winchain.chainbill.bill.base.service.CbDfrlService;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.BillExpQueryService;
import com.winchain.provider.expiration.service.CbCreditService;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpDlyInsExeCmd implements ICommand<BillExpirationEvent> {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private BillExpQueryService billExpQueryService;
	@Autowired
	private CbDfrlService cbDfrlService;
	@Autowired
	private CbCreditService cbCreditService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		BillExpirationEvent event = (BillExpirationEvent) context.getSource();
		final String expDate = event.getDate();
		String grpId = event.getGrpId();
		List<CbDfrl> dfrls = this.billExpQueryService.selectExpDlyInsBills(expDate, grpId, "1");
		for (final CbDfrl cbDfrl : dfrls) {
			this.logger.info("����������������");
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						CbDfrl dfrl = BillExpDlyInsExeCmd.this.cbDfrlService.selectAndLockByKey(cbDfrl.getDfrlId());
						if (!cbDfrl.getDfrlState().equals(dfrl.getDfrlState())) {
							BillExpDlyInsExeCmd.this.logger.warn("CbDfrl state Has Changed.");
							return;
						}
						BillExpDlyInsExeCmd.this.cbCreditService.saveCbCredit(null, null, cbDfrl, expDate);
					}
				}, new int[0]);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error(getClass() + "��������", e);
				throw new ExtException(e.getMessage());
			}
		}
		return false;
	}
}
